package com.yuelife.service.controller;

import com.github.pagehelper.PageInfo;
import com.yuelife.service.utils.AliyunOSSUtil;
import com.yuelife.service.pojo.SStore;
import com.yuelife.service.service.SStoreService;
import com.yuelife.service.utils.AliyunossUtils;
import com.yuelife.service.utils.FileUploadResult;
import entity.JwtUtil;
import entity.Result;
import entity.StatusCode;
import io.jsonwebtoken.Claims;
import io.swagger.annotations.*;
import io.swagger.models.auth.In;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Date;
import java.util.List;
import java.util.Map;

/****
 * @Author:admin
 * @Description:
 * @Date 2019/6/14 0:18
 *****/
@Api(value = "SStoreController")
@RestController
@RequestMapping("/sStore")
@CrossOrigin
public class SStoreController {

    @Autowired
    private SStoreService sStoreService;
    @Resource
    private AliyunOSSUtil aliyunOSSUtil;//第一个工具包
    @Resource
    private AliyunossUtils aliyunossUtils;//第二个工具包

    /***
     * SStore分页条件搜索实现
     * @param sStore
     * @param page
     * @param size
     * @return
     */
    @ApiOperation(value = "SStore条件分页查询", notes = "分页条件查询SStore方法详情", tags = {"SStoreController"})
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "path", name = "page", value = "当前页", required = true, dataType = "Integer"),
            @ApiImplicitParam(paramType = "path", name = "size", value = "每页显示条数", required = true, dataType = "Integer")
    })
    @PostMapping(value = "/search/{page}/{size}")
    public Result<PageInfo> findPage(@RequestBody(required = false) @ApiParam(name = "SStore对象", value = "传入JSON数据", required = false) SStore sStore, @PathVariable int page, @PathVariable int size) {
        //调用SStoreService实现分页条件查询SStore
        PageInfo<SStore> pageInfo = sStoreService.findPage(sStore, page, size);
        return new Result(true, StatusCode.OK, "查询成功", pageInfo);
    }

    /***
     * SStore分页搜索实现
     * @param page:当前页
     * @param size:每页显示多少条
     * @return
     */
    @ApiOperation(value = "SStore分页查询", notes = "分页查询SStore方法详情", tags = {"SStoreController"})
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "path", name = "page", value = "当前页", required = true, dataType = "Integer"),
            @ApiImplicitParam(paramType = "path", name = "size", value = "每页显示条数", required = true, dataType = "Integer")
    })
    @GetMapping(value = "/search/{page}/{size}")
    public Result<PageInfo> findPage(@PathVariable int page, @PathVariable int size) {
        //调用SStoreService实现分页查询SStore
        PageInfo<SStore> pageInfo = sStoreService.findPage(page, size);
        return new Result<PageInfo>(true, StatusCode.OK, "查询成功", pageInfo);
    }

    /***
     * 多条件搜索品牌数据
     * @param sStore
     * @return
     */
    @ApiOperation(value = "SStore条件查询", notes = "条件查询SStore方法详情", tags = {"SStoreController"})
    @PostMapping(value = "/search")
    public Result<List<SStore>> findList( @ApiParam(name = "SStore对象", value = "传入JSON数据", required = false) SStore sStore) {
        //调用SStoreService实现条件查询SStore
        List<SStore> list = sStoreService.findList(sStore);
        //System.out.println(list);
        return new Result<List<SStore>>(true, StatusCode.OK, "查询成功", list);
    }

    @PostMapping(value = "/searchby")
    public Result<List<SStore>> findListby( @ApiParam(name = "SStore对象", value = "传入JSON数据", required = false) SStore sStore) {
        //调用SStoreService实现条件查询SStore
        List<SStore> list = sStoreService.findbycondition(sStore);
        //System.out.println(list);
        return new Result<List<SStore>>(true, StatusCode.OK, "查询成功", list);
    }

    /***
     * 根据ID删除品牌数据
     * @param id
     * @return
     */
    @ApiOperation(value = "SStore根据ID删除", notes = "根据ID删除SStore方法详情", tags = {"SStoreController"})
    @ApiImplicitParam(paramType = "path", name = "id", value = "主键ID", required = true, dataType = "Integer")
    @DeleteMapping(value = "/{id}")
    public Result delete(@PathVariable Integer id) {
        //调用SStoreService实现根据主键删除
        sStoreService.delete(id);
        return new Result(true, StatusCode.OK, "删除成功");
    }

    /***
     * 修改SStore数据
     * @param sStore
     * @param id
     * @return
     */
    @ApiOperation(value = "SStore根据ID修改", notes = "根据ID修改SStore方法详情", tags = {"SStoreController"})
    @ApiImplicitParam(paramType = "path", name = "id", value = "主键ID", required = true, dataType = "Integer")
    @PutMapping(value = "/{id}")
    public Result update(@RequestBody @ApiParam(name = "SStore对象", value = "传入JSON数据", required = false) SStore sStore, @PathVariable Integer id) {
        //设置主键值
        sStore.setStoreId(id);
        //调用SStoreService实现修改SStore
        sStoreService.update(sStore);
        return new Result(true, StatusCode.OK, "修改成功");
    }

    /***
     * 新增SStore数据
     * @param sStore
     * @return
     */
    @ApiOperation(value = "SStore添加", notes = "添加SStore方法详情", tags = {"SStoreController"})
    @PostMapping
    public Result add(@RequestBody @ApiParam(name = "SStore对象", value = "传入JSON数据", required = true) SStore sStore) {
        //调用SStoreService实现添加SStore

        sStoreService.add(sStore);
        return new Result(true, StatusCode.OK, "添加成功");
    }


    //商店入驻注册同时，上传图片，保存到oss云相册（使用了AliyunossUtils和FileUploadResult工具包）
    @PostMapping("/upp")
    public Result addStoreupp(@RequestParam(value = "file", required = false) MultipartFile file, SStore sStore) throws IOException {
        //调用oss工具类上传图片并保存到数据库
        String s = aliyunOSSUtil.uploadFile(file.getInputStream());
        //System.out.println(upload);
        sStore.setImg(s);
        //添加时间
        //sStore.setStoreCreatetime(new Date());
        //调用SStoreService实现添加SStore
        sStoreService.add(sStore);
        return new Result(true, StatusCode.OK, "添加成功");
    }

    /***
     * 根据ID查询SStore数据
     * @param id
     * @return
     */
    @ApiOperation(value = "SStore根据ID查询", notes = "根据ID查询SStore方法详情", tags = {"SStoreController"})
    //@ApiImplicitParam(paramType = "path", name = "id", value = "主键ID", required = true, dataType = "Integer")
    @PostMapping("/find")
    @ResponseBody
    public Result<SStore> findById(@RequestParam(value = "id", required = true) Integer id) {
        //调用SStoreService实现根据主键查询SStore
        SStore sStore = sStoreService.findById(id);
        return new Result<SStore>(true, StatusCode.OK, "查询成功", sStore);
    }

    /***
     * 查询SStore全部数据
     * @return
     */
    @ApiOperation(value = "查询所有SStore", notes = "查询所SStore有方法详情", tags = {"SStoreController"})
    @GetMapping
    public Result<List<SStore>> findAll() {
        //调用SStoreService实现查询所有SStore
        List<SStore> list = sStoreService.findAll();
        return new Result<List<SStore>>(true, StatusCode.OK, "查询成功", list);
    }

    //商店入驻注册同时，上传图片，保存到oss云相册（使用了AliyunOSSUtil工具包）
    @PostMapping("/add")
    public Result addStore(@RequestParam(value = "file", required = false) MultipartFile file, SStore sStore) throws IOException {
        //调用oss工具类上传图片并保存到数据库
        FileUploadResult upload = aliyunossUtils.upload(file);
        //System.out.println(upload);
        String img = upload.getName();
        sStore.setImg(img);
        //添加时间
        sStore.setStoreCreatetime(new Date());
        //调用SStoreService实现添加SStore
        sStoreService.add(sStore);
        return new Result(true, StatusCode.OK, "添加成功");
    }


    /**
     * 注册
     * @param file
     * @param
     * @return
     */
    @PostMapping("/regist")
    public Result regist(@RequestParam(value = "file",required = false) MultipartFile file, SStore sStore) {
        try {
            //判断用户是否存在
            SStore sStoreTellphone = sStoreService.findbystoreTellphone(sStore.getStoreTellphone());
            if(sStoreTellphone!=null) {
                return new Result(false, StatusCode.USEREXIST, "店铺已存在");
            }
            //将加密后的密码存入数据库
            String pwdMD5 = code(sStore.getStorePassword());
            sStore.setStorePassword(pwdMD5);
            //存入图片
            FileUploadResult upload = aliyunossUtils.upload(file);
            String img = upload.getName();
            sStore.setImg(img);
            //注册时间
            sStore.setStoreCreatetime(new Date());
            sStoreService.add(sStore);
            return new Result(true, StatusCode.OK, "注册店铺成功");
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, StatusCode.ERROR, e.getMessage());
        }
    }

    /**
     * md5加密方法
     * @param str
     * @return
     */
    private static String code(String str) {
        try {
            MessageDigest md = MessageDigest.getInstance("MD5");
            md.update(str.getBytes());
            byte[] byteDigest = md.digest();
            int i;
            StringBuffer buf = new StringBuffer("");
            for (int offset = 0; offset < byteDigest.length; offset++) {
                i = byteDigest[offset];
                if (i < 0) {
                    i += 256;
                }
                if (i < 16) {
                    buf.append("0");
                }
                buf.append(Integer.toHexString(i));
            }
            //32位加密
            return buf.toString();
            // 16位的加密
            //return buf.toString().substring(8, 24);
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
            return null;
        }
    }


    /**商家入驻：登录
     *
     * @param
     * @return
     */
    @GetMapping("/logins")
    public Result logins(SStore sStore) {
        if (sStore == null) {
            return new Result(false,StatusCode.ERROR,"登录失败");
        }
        String storeTellphone = sStore.getStoreTellphone();
        String storePassword = sStore.getStorePassword();
        storePassword=code(storePassword);
        try {
            if (StringUtils.isEmpty(storeTellphone) || StringUtils.isEmpty(storePassword)) {
                return new Result(false,StatusCode.ERROR,"账号或者密码不能为空");
            }
            if (sStoreService.findbystoreTellphone(storeTellphone) == null) {
                return new Result(false,StatusCode.ERROR,"用户名或者密码不匹配");
            }
            SStore  findBytelAndPassword= sStoreService.findbyTellandpassword(storeTellphone, storePassword);
            if (findBytelAndPassword == null) {
                return new Result(false,StatusCode.ERROR,"用户名或者密码不正确");
            } else if(!findBytelAndPassword.getStoreStatus().equals("1")){
                return new Result(false,StatusCode.ERROR,"后台还在审核中");

            } else{
                String token = JwtUtil.createJwt(findBytelAndPassword.getStoreId() + "", findBytelAndPassword.getStoreName());
                System.out.println("id"+findBytelAndPassword.getStoreId());
                System.out.println("name"+findBytelAndPassword.getStoreName());
                return new Result(true, StatusCode.OK, "登陆成功", token);
            }
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false,StatusCode.ERROR,e.getMessage());
        }
    }





    /**
     * 检查token不正确返回
     * @return
     */
    @RequestMapping("/loginmessage")
    public String loginmessage(){
        return "请登录";
    }

    /**
     * 登录以后加载店家信息
     * @param request
     * @return
     */
    @PostMapping("/profile")
    public Result profile(HttpServletRequest request){
        try {

            //从请求头获取token数据
            String authorization = request.getHeader("Authorization");
            if(StringUtils.isEmpty(authorization)){
                throw new Exception();
            }
            String token = authorization.replace("Bearer", "");
            //解析token
            Claims claims = JwtUtil.parseJwt(token);
            String id = (String) claims.get("id");
            System.out.println("token"+id);
            SStore byId = sStoreService.findById(Integer.valueOf(id));
            return new Result(true,StatusCode.OK,"加载成功",byId);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(true,StatusCode.ERROR,"加载失败");
        }
    }

}
